package  
{
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import org.flixel.*;
	/**
	 * ...
	 * @author morgan
	 */
	public class Grass extends FlxSprite
	{
		private var fg:FlxSprite;
		private var blades:Array = [];
		
		public var wind:Number = 0;
		public var windChangeTimer:Number = 0;
		public function Grass(foreground:FlxSprite) 
		{
			super(0, 0);
			fg = foreground;
			makeGraphic(fg.width, fg.height, 0x00000000);
		}
		
		public function generateGrass():void
		{
			for (var i:int = 0; i < width; i += Math.random()*2)
			{
				var col:BitmapData = new BitmapData(1, height);
				col.copyPixels(fg.pixels, new Rectangle(i, 0, 1, height), new Point(0, 0), fg.pixels, new Point(i,0), true);
				var br:Rectangle = col.getColorBoundsRect(0xffffffff, 0xff000000, true);
				var grassInstance:Array = [i, br.y, Math.random() * 3 + 2, 0, (Math.random() * 2 - 1) / 2];
				blades.push(grassInstance);
			}	
		}
		
		override public function update():void 
		{
			super.update();	
			
			windChangeTimer -= FlxG.elapsed;
			if (windChangeTimer <= 0)
			{
				wind = (Math.random() * 2 - 1) / 2;
				windChangeTimer = Math.random() * 2 + 0.25;
			}
			
			var h:Human = (FlxG.state as GameState).human;
			
			for each (var b:Array in blades)
			{
				var inf:Number = Math.abs((h.x+h.width/2) - b[0])+1;
				if (inf <= 10 && Math.abs((h.y + h.height) - b[1]) <= 5)
				{
					if (h.velocity.x < 0) { b[3] = Math.max(b[3] - (20/inf) * FlxG.elapsed, -3); }
					else if (h.velocity.x > 0) { b[3] = Math.min(b[3] + (20/inf) * FlxG.elapsed, 3); }
				}
				b[3] = b[3] * 0.95 + wind * 0.05;
				b[3] *= 0.99;
			}
		}
		
		override public function draw():void 
		{
			super.draw();
			for each (var b:Array in blades)
			{
				var bx:Number = b[0] - FlxG.camera.scroll.x ;
				var by:int = b[1];
				var by2:int = b[2];
				by2 -= Math.abs(b[3]);
				for (var ys:int = b[1]; ys > by - by2; ys--)
				{
					bx += b[3] + b[4];
					FlxG.camera.buffer.setPixel32(bx, ys, 0xff000000);
				}
				
			}				
		}
	}

}